package service

import (
	"dataaysn/internal/model"
	"dataaysn/internal/repository"

	"github.com/gin-gonic/gin"

	"strconv"
)

type HisDoctorService struct {
	repo repository.HisDoctorRepository
}

func NewHisDoctorService(repo repository.HisDoctorRepository) *HisDoctorService {
	return &HisDoctorService{repo: repo}
}

func (s *HisDoctorService) CreateDoctor(c *gin.Context) {
	var doctor model.HisDoctor
	if err := c.ShouldBindJSON(&doctor); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}

	if err := s.repo.Create(&doctor); err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}

	c.JSON(200, doctor)
}

func (s *HisDoctorService) GetDoctorByID(c *gin.Context) {
	id := c.Param("id")
	idUint, errConv := strconv.ParseUint(id, 10, 64)
	if errConv != nil {
		// 转换失败，返回错误响应
		c.JSON(400, gin.H{"error": "invalid id format"})
		return
	}
	doctor, err := s.repo.GetByID(uint(idUint))
	if err != nil {
		c.JSON(404, gin.H{"error": "not found"})
		return
	}
	c.JSON(200, doctor)
}

func (s *HisDoctorService) GetDoctorByCode(c *gin.Context) {
	code := c.Param("code")
	doctor, err := s.repo.GetByDoctorCode(code)
	if err != nil {
		c.JSON(404, gin.H{"error": "not found"})
		return
	}
	c.JSON(200, doctor)
}

func (s *HisDoctorService) UpdateDoctor(c *gin.Context) {
	var doctor model.HisDoctor
	if err := c.ShouldBindJSON(&doctor); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}

	if err := s.repo.Update(&doctor); err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}

	c.JSON(200, doctor)
}

func (s *HisDoctorService) DeleteDoctor(c *gin.Context) {
	id := c.Param("id")
	idUint, errConv := strconv.ParseUint(id, 10, 64)
	if errConv != nil {
		// 转换失败，返回错误响应
		c.JSON(400, gin.H{"error": "invalid id format"})
		return
	}
	if err := s.repo.Delete(uint(idUint)); err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}
	c.JSON(200, gin.H{"message": "deleted"})
}

func (s *HisDoctorService) ListDoctorsByHospital(c *gin.Context) {
	hospitalCode := c.Param("hospitalCode")
	doctors, err := s.repo.ListByHospital(hospitalCode)
	if err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}
	c.JSON(200, doctors)
}

func (s *HisDoctorService) ListDoctorsByDepartment(c *gin.Context) {
	deptCode := c.Param("deptCode")
	doctors, err := s.repo.ListByDepartment(deptCode)
	if err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}
	c.JSON(200, doctors)
}
